﻿using AutoScaleHelper;
using HZH_Controls.Controls;
using LituoPro.util;
using System;
using System.Diagnostics;
using System.Drawing.Drawing2D;
using System.Drawing;
using System.IO.Ports;
using System.Windows.Forms;
using LituoPro.network;
using System.Collections.Generic;
using LituoPro.ltcore;
using LituoPro.ltcore.service;
using LituoPro.ltcore.entity;
using System.Threading;
using LituoPro.log;
using System.ComponentModel;
using System.Collections;
using System.Xml.Linq;
using LituoPro.constant;
using LituoPro.ltcore.constant;
using LituoPro.database;
using LituoPro.database.entity;
using LituoPro.database.entity.res;
using LituoPro.database.entity.vo;

namespace LituoPro
{
    public partial class MainForm : Form
    {

        private AutoScale autoScale = null;

        private string selectedPortValue = "";

        private SerialPort serialPort;

        private bool sendDateFlag = false;

        private string GROUND_EVENT_ID = "";

        private string LOCO_EVENT_ID = "";

        private SqlLiteDataHelper sqlLiteDataHelper = new SqlLiteDataHelper();


        private AutoScale getAutoScaleInstance()
        {
            if (autoScale == null)
            {
                autoScale = new AutoScale();
            }

            return autoScale;
        }




        public MainForm()
        {
            InitializeComponent();
            this.getAutoScaleInstance();
            autoScale.SetContainer(this);
            this.WindowState = FormWindowState.Maximized;
            this.CloseDataButton.Enabled = false;
            this.MsgLabel.Visible = false;
            this.initComboBoxDevPortList();
            this.startTimer();
            this.initDataGridViewColumn();
            this.getPressureDataSource();
            LogHelper.Info("MainWindows InitializeComponent  Success");
        }

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }

        private void MainForm_SizeChanged(object sender, EventArgs e)
        {
            this.SuspendLayout();
            this.getAutoScaleInstance();
            autoScale.UpdateControlsLayout();
            this.ResumeLayout();
        }

        private string initSerialPort(string selectedPortValue)
        {
            serialPort = SerialPortUtil.initSerialPort(selectedPortValue);
            serialPort.DataReceived += MainWindowsSerialPort_DataReceived;
            string res = SerialPortUtil.openSerialPort(serialPort);
            return res;
        }

        private void MainWindowsSerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            lock (serialPort)
            {
                try
                {
                    sendDateFlag = true;
                    this.handlerSignalLampLedInvoke();
                }
                catch (Exception ex)
                {
                    string errorMsg = ex.Message;
                    Debug.WriteLine("error:" + errorMsg);
                    LogHelper.Error("MainWindowsSerialPort_DataReceived_Error:" + errorMsg);
                    if (this.MsgLabel.InvokeRequired)
                    {
                        this.Invoke(new Action(() =>
                        {
                            this.MsgLabel.Text = errorMsg;
                            this.MsgLabel.ForeColor = Color.Red;
                        }));
                    }
                }finally 
                { 
                    sendDateFlag = false;
                }
            }
        }


        private void handlerSignalLampLedInvoke()
        {
            Byte[] DI_Bytes = null;
            Byte[] inputBuf = new Byte[256];
            Thread.Sleep(1000);//延时处理缓存区数据
            serialPort.Read(inputBuf, 0, inputBuf.Length);
            List<Byte[]> byteList = NetWorkHandle.getNetWorkPackage(inputBuf);
            if (byteList != null)
            {
                Byte[] bytes = byteList[0];
                DataVerify dataVerify = new DataVerify();
                Boolean flagVerify = dataVerify.verify(bytes, 106, 105);
                if (flagVerify)
                {
                    ReportService reportService = new ReportService();
                    RetDataEntity retDataEntity = reportService.convert(bytes);
                    Byte[] tableTypeByte = retDataEntity.tableTypeByte;
                    if (tableTypeByte[0] == TableTypeConstant.GROUND_TABLE_TYPE) 
                    {
                        LogHelper.Info("地面数据校验成功: " + ConvertUtil.ConvertToHexString(bytes));
                        LogHelper.Debug("地面数据校验成功: " + ConvertUtil.ConvertToHexString(bytes));
                        if (retDataEntity.dataByte != null)
                        {
                            LogHelper.Info("CPU_ID:" + ConvertUtil.ConvertToHexString(retDataEntity.cpuIdByte));
                            DI_Bytes = retDataEntity.dataByte.diByte;
                            string  CURRENT_GROUND_EVENT_ID = ConvertUtil.ConvertToHexString(retDataEntity.dataByte.eventIdByte);
                            if (!GROUND_EVENT_ID.Equals(CURRENT_GROUND_EVENT_ID) 
                                || SystemConstant.E_TRACK_NOx_DATA_UPDATE.Equals(CURRENT_GROUND_EVENT_ID)) {
                                insertRetMessage(CURRENT_GROUND_EVENT_ID, TableTypeConstant.GROUND_TABLE_TYPE, retDataEntity.dataByte);
                            }
                            GROUND_EVENT_ID = CURRENT_GROUND_EVENT_ID;
                        }
                    }
                    if (tableTypeByte[0] == TableTypeConstant.LOCO_TABLE_TYPE)
                    {
                        LogHelper.Info("机车数据校验成功: " + ConvertUtil.ConvertToHexString(bytes));
                        LogHelper.Debug("机车数据校验成功: " + ConvertUtil.ConvertToHexString(bytes));
                        if (retDataEntity.dataByte != null)
                        {
                            string CURRENT_LOCO_EVENT_ID = ConvertUtil.ConvertToHexString(retDataEntity.dataByte.eventIdByte);
                            if (!LOCO_EVENT_ID.Equals(CURRENT_LOCO_EVENT_ID)
                                || SystemConstant.E_LOCOMOTIVE_CYLINDER_PRESS.Equals(CURRENT_LOCO_EVENT_ID)
                                || SystemConstant.E_LOCOMOTIVE_DATA_UPDATE.Equals(CURRENT_LOCO_EVENT_ID)
                                )
                            {
                                insertRetMessage(CURRENT_LOCO_EVENT_ID, TableTypeConstant.LOCO_TABLE_TYPE, retDataEntity.dataByte);
                            }
                            LOCO_EVENT_ID = CURRENT_LOCO_EVENT_ID;
                        }
                    }
                }
                else
                {
                    LogHelper.Info("数据校验失败:" + ConvertUtil.ConvertToHexString(bytes));
                    LogHelper.Debug("数据校验失败: " + ConvertUtil.ConvertToHexString(bytes));
                    Debug.WriteLine("数据校验失败:" + ConvertUtil.ConvertToHexString(bytes));
                    /* this.Invoke(new Action(() =>
                     {
                         this.MsgLabel.Text = SystemConstant.DATA_CHECK_SUM_MSG_ERROR;
                         this.MsgLabel.ForeColor = Color.Red;
                     }));*/
                }
            }
            if (DI_Bytes != null && DI_Bytes.Length == 10)
            {
                ushort us_DI_0 = DI_Bytes[0];
                if (this.ucSignalLampLed5.InvokeRequired)
                {
                    this.Invoke(new Action(() =>
                    {
                        if (us_DI_0 == 0)
                        {
                            this.ucSignalLampLed5.LampColor = new Color[] { Color.Green };
                        }
                        else
                        {
                            this.ucSignalLampLed5.LampColor = new Color[] { Color.Red };
                        }
                    }));
                }
                ushort us_DI_1 = DI_Bytes[1];
                if (this.ucSignalLampLed3.InvokeRequired)
                {
                    this.Invoke(new Action(() =>
                    {
                        if (us_DI_1 == 0)
                        {
                            this.ucSignalLampLed3.LampColor = new Color[] { Color.Green };
                        }
                        else
                        {
                            this.ucSignalLampLed3.LampColor = new Color[] { Color.Red };
                        }
                    }));
                }
                ushort us_DI_2 = DI_Bytes[2];
                if (this.ucSignalLampLed6.InvokeRequired)
                {
                    this.Invoke(new Action(() =>
                    {
                        if (us_DI_2 == 0)
                        {
                            this.ucSignalLampLed6.LampColor = new Color[] { Color.Green };
                        }
                        else
                        {
                            this.ucSignalLampLed6.LampColor = new Color[] { Color.Red };
                        }
                    }));
                }
                ushort us_DI_3 = DI_Bytes[3];
                if (this.ucSignalLampLed4.InvokeRequired)
                {
                    this.Invoke(new Action(() =>
                    {
                        if (us_DI_3 == 0)
                        {
                            this.ucSignalLampLed4.LampColor = new Color[] { Color.Green };
                        }
                        else
                        {
                            this.ucSignalLampLed4.LampColor = new Color[] { Color.Red };
                        }
                    }));
                }
                ushort us_DI_4 = DI_Bytes[4];
                if (this.ucSignalLampLed1.InvokeRequired)
                {
                    this.Invoke(new Action(() =>
                    {
                        if (us_DI_4 == 0)
                        {
                            this.ucSignalLampLed1.LampColor = new Color[] { Color.Green };
                        }
                        else
                        {
                            this.ucSignalLampLed1.LampColor = new Color[] { Color.Red };
                        }
                    }));
                }
                ushort us_DI_5 = DI_Bytes[5];
                if (this.ucSignalLampLed2.InvokeRequired)
                {
                    this.Invoke(new Action(() =>
                    {
                        if (us_DI_5 == 0)
                        {
                            this.ucSignalLampLed2.LampColor = new Color[] { Color.Green };
                        }
                        else
                        {
                            this.ucSignalLampLed2.LampColor = new Color[] { Color.Red };
                        }
                    }));
                }
                ushort us_DI_6 = DI_Bytes[6];
                if (this.ucSignalLampLed8.InvokeRequired)
                {
                    this.Invoke(new Action(() =>
                    {
                        if (us_DI_6 == 0)
                        {
                            this.ucSignalLampLed8.LampColor = new Color[] { Color.Red };
                        }
                        else
                        {
                            this.ucSignalLampLed8.LampColor = new Color[] { Color.Blue };
                        }
                    }));
                }
                ushort us_DI_7 = DI_Bytes[7];
                if (this.ucSignalLampLed10.InvokeRequired)
                {
                    this.Invoke(new Action(() =>
                    {
                        if (us_DI_7 == 0)
                        {
                            this.ucSignalLampLed10.LampColor = new Color[] { Color.Red };
                        }
                        else
                        {
                            this.ucSignalLampLed10.LampColor = new Color[] { Color.Blue };
                        }
                    }));
                }
                ushort us_DI_8 = DI_Bytes[8];
                if (this.ucSignalLampLed7.InvokeRequired)
                {
                    this.Invoke(new Action(() =>
                    {
                        if (us_DI_8 == 0)
                        {
                            this.ucSignalLampLed7.LampColor = new Color[] { Color.Red };
                        }
                        else
                        {
                            this.ucSignalLampLed7.LampColor = new Color[] { Color.Blue };
                        }
                    }));
                }
                ushort us_DI_9 = DI_Bytes[9];
                if (this.ucSignalLampLed9.InvokeRequired)
                {
                    this.Invoke(new Action(() =>
                    {
                        if (us_DI_9 == 0)
                        {
                            this.ucSignalLampLed9.LampColor = new Color[] { Color.Red };
                        }
                        else
                        {
                            this.ucSignalLampLed9.LampColor = new Color[] { Color.Blue };
                        }
                    }));
                }
                if (this.MsgLabel.InvokeRequired)
                {
                    this.Invoke(new Action(() =>
                    {
                        this.MsgLabel.Text = SystemConstant.READ_SERIAL_PORT_RET_MSG_SUCCESS;
                        this.MsgLabel.ForeColor = Color.Green;
                    }));
                }
            }
        }




        private void initComboBoxDevPortList()
        {
            string[] ports = SerialPortUtil.getDevPorts();
            foreach (string port in ports)
            {
                portComboBox.Items.Add(port);
            }
        }



        private void ReadDataButton_Click(object sender, EventArgs e)
        {
            if (portComboBox.SelectedItem != null)
            {
                string res = "";
                BackgroundWorker worker = new BackgroundWorker();
                worker.DoWork += (s1, e1) =>
                {
                    res = this.initSerialPort(selectedPortValue);
                };
                worker.RunWorkerCompleted += (s2, e2) =>
                {
                    this.MsgLabel.Text = res;
                    if (SystemConstant.OPEN_SERIAL_PORT_RET_MSG_SUCCESS.Equals(res))
                    {
                        this.MsgLabel.ForeColor = Color.Green;
                    }
                    else {
                        this.MsgLabel.ForeColor = Color.Red;
                    }
                    this.MsgLabel.Visible = true;
                    this.ReadDataButton.Enabled = false;
                    this.CloseDataButton.Enabled = true;
                    this.portComboBox.Enabled = false;  
                };
                // 开始异步操作
                worker.RunWorkerAsync();
            }
            else 
            {
                MessageBox.Show("请选择端口!");
            }
         
        }



        private void CloseDataButton_Click(object sender, EventArgs e)
        {
            string res = "";
            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += (s1, e1) =>
            {
                res = SerialPortUtil.closeSerialPort(serialPort);
                SerialPortUtil.clearSerialPort();
                serialPort = null;  
            };
            worker.RunWorkerCompleted += (s2, e2) =>
            {
                this.MsgLabel.Text = res;
                if (SystemConstant.CLOSE_SERIAL_PORT_RET_MSG_SUCCESS.Equals(res))
                {
                    this.MsgLabel.ForeColor = Color.Green;
                }
                else
                {
                    this.MsgLabel.ForeColor = Color.Red;
                }
                this.ReadDataButton.Enabled = true;
                this.CloseDataButton.Enabled = false;
                this.portComboBox.Enabled = true;
            };
            // 开始异步操作
            worker.RunWorkerAsync();

        }

        private void portComboBox_SelectedValueChanged(object sender, EventArgs e)
        {
            selectedPortValue = portComboBox.SelectedItem.ToString();
            SerialPortUtil.clearSerialPort();

        }

        private void sysTimer_Tick(object sender, EventArgs e)
        {
            this.SysTime.Text = DateTime.Now.ToString();
        }

        private void PowerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PowerForm powerForm = new PowerForm();
            powerForm.Show();
            powerForm.Visible = false;
            powerForm.ShowDialog();
        }

        private void AboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutForm aboutForm = new AboutForm();
            aboutForm.Show();
            aboutForm.Visible = false;
            aboutForm.ShowDialog();
        }

        private void insertRetMessage(string eventId, byte tableTypeByte, DataByte dataByte)
        {
            LtRetMessageEntity ltRetMessage = new LtRetMessageEntity();
            ltRetMessage.id = CommonUtil.getUUid();
            ltRetMessage.eventId = eventId; 
            ltRetMessage.devType = tableTypeByte.ToString("x2");
            ltRetMessage.aiContent = ConvertUtil.ConvertToHexString(dataByte.aiByte);
            ltRetMessage.diContent = ConvertUtil.ConvertToHexString(dataByte.diByte);
            ltRetMessage.aoContent = ConvertUtil.ConvertToHexString(dataByte.a0Byte);
            ltRetMessage.doContent = ConvertUtil.ConvertToHexString(dataByte.d0Byte);
            DateTime now = DateTime.Now;
            string strCreatTime = now.ToString("yyyy-MM-dd HH:mm:ss");
            ltRetMessage.createTime = strCreatTime;
            sqlLiteDataHelper.InsertLtRetMessageData(ltRetMessage);
        }
        private void sendDateTimer_Tick(object sender, EventArgs e)
        {
            try
            {
                if (!sendDateFlag && serialPort != null)
                {
                    SendDateTimeService sendDateTimeService = new SendDateTimeService();
                    Byte[] reqSendByte = sendDateTimeService.getSendByte();
                    SerialPortUtil.sendData(serialPort, reqSendByte);
                    LogHelper.Info("发送数据成功:" + ConvertUtil.ConvertToHexString(reqSendByte));
                    LogHelper.Debug("发送数据成功:" + ConvertUtil.ConvertToHexString(reqSendByte));
                }
                else {
                    LogHelper.Info("定时发送状态未通过:sendDateFlag=>" + sendDateFlag + ",serialPort=>" + serialPort);
                }
            
            }
            catch (Exception ex)
            {
                LogHelper.Info("发送数据error:" + ex.Message);
            }
           
        }

        private void DataDebugToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DataDebugForm dataDebugForm = new DataDebugForm();
            dataDebugForm.Show();
            dataDebugForm.Visible = false;
            dataDebugForm.ShowDialog();
        }

        private void initDataGridViewColumn()
        {
            List<DataGridViewColumnEntity> lstCulumns = new List<DataGridViewColumnEntity>();
            lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "createTime", HeadText = "时间", Width = 350, WidthType = SizeType.Absolute });
            lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "pressure", HeadText = "压力(Kpa)", Width = 350, WidthType = SizeType.Absolute });
            this.ucDataGridView.Columns = lstCulumns;
        }


        private void getPressureDataSource()
        {
            List<object> lstSource = new List<object>();
            List<QueryAiDataRes> aiDatas = sqlLiteDataHelper.QueryAiData();
            if (aiDatas != null && aiDatas.Count > 0) 
            {
                
                foreach (QueryAiDataRes aiData in aiDatas) 
                {
                    string aiContent = aiData.aiContent;
                    ushort result = 0;
                    if (aiContent != null && aiContent.Length >= 4)
                    {
                        string strByte0 = aiContent.Substring(0, 2);
                        string strByte1 = aiContent.Substring(2, 2);
                        byte byte0 = Convert.ToByte(strByte0, 16);
                        byte byte1 = Convert.ToByte(strByte1, 16);
                        byte[] hexBytes = { byte1,byte0 };
                        result = BitConverter.ToUInt16(hexBytes, 0);
                    }
                    PressureDataVo pressureDataVo = new PressureDataVo();
                    pressureDataVo.pressure = this.calculatePressure(result);
                    pressureDataVo.createTime = aiData.createTime;
                    lstSource.Add(pressureDataVo);
                }
            }
            this.ucDataGridView.DataSource = lstSource;
        }

        private string calculatePressure(ushort result) 
        {
            double mA = result * 0.9155 / 1000;
            if (mA < 4)
            {
                //低于4mA 压力为0kPa
                return "0";
            }
            double presure = (mA - 4) * 102.5;
            return presure.ToString("F3");
        }

        private void dataTimer_Tick(object sender, EventArgs e)
        {
            this.getPressureDataSource();
        }

        private void startTimer()
        {
            this.sysTimer.Start();
           // this.sendDateTimer.Start();
            this.dataTimer.Start();
        }
    }
}
